package cn.iocoder.yudao.module.system.controller.admin.mini.other.lottery.controller.admin.lottery;

import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.mybatis.core.dataobject.BaseDO;
import cn.iocoder.yudao.module.system.controller.admin.mini.group.goods.dal.dataobject.groupgoods.GroupGoodsDO;
import cn.iocoder.yudao.module.system.controller.admin.mini.group.goods.dal.mysql.groupgoods.GroupGoodsMapper;
import cn.iocoder.yudao.module.system.controller.admin.mini.group.order.dal.dataobject.grouporder.GroupOrderDO;
import cn.iocoder.yudao.module.system.controller.admin.mini.group.order.dal.mysql.grouporder.GroupOrderMapper;
import cn.iocoder.yudao.module.system.controller.admin.mini.orderInfo.order.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.system.controller.admin.mini.orderInfo.order.dal.mysql.order.OrderMapper;
import cn.iocoder.yudao.module.system.controller.admin.mini.other.lottery.controller.admin.lottery.vo.*;
import cn.iocoder.yudao.module.system.controller.admin.mini.other.lottery.convert.lottery.LotteryConvert;
import cn.iocoder.yudao.module.system.controller.admin.mini.other.lottery.dal.dataobject.lottery.LotteryDO;
import cn.iocoder.yudao.module.system.controller.admin.mini.other.lottery.dal.dataobject.lottery.LotteryInfoDO;
import cn.iocoder.yudao.module.system.controller.admin.mini.other.lottery.dal.dataobject.lottery.LotteryUser;
import cn.iocoder.yudao.module.system.controller.admin.mini.other.lottery.dal.mysql.lottery.LotteryInfoMapper;
import cn.iocoder.yudao.module.system.controller.admin.mini.other.lottery.dal.mysql.lottery.LotteryMapper;
import cn.iocoder.yudao.module.system.controller.admin.mini.other.lottery.dal.mysql.lottery.LotteryUserMapper;
import cn.iocoder.yudao.module.system.controller.admin.mini.other.lottery.service.lottery.LotteryService;
import cn.iocoder.yudao.module.system.controller.admin.mini.userInfo.user.dal.dataobject.user.UserDO;
import cn.iocoder.yudao.module.system.controller.admin.mini.userInfo.user.dal.mysql.user.QdUserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.*;

@Tag(name = "管理后台 - 抽奖")
@RestController
@RequestMapping("/qd/lottery")
@Validated
public class LotteryController {

    @Resource
    private LotteryService lotteryService;
    @Resource
    private LotteryMapper lotteryMapper;
    @Resource
    private LotteryUserMapper lotteryUserMapper;
    @Resource
    LotteryInfoMapper lotteryInfoMapper;
    @Resource
    GroupGoodsMapper groupGoodsMapper;
    @Resource
    GroupOrderMapper groupOrderMapper;
    @Resource
    OrderMapper orderMapper;
    @Resource
    QdUserMapper userMapper;

    @GetMapping("change")
    @Operation(summary = "兑换奖品")
    public CommonResult change(Integer id,String code){
        LotteryInfoDO vo = lotteryInfoMapper.selectById(id);
        if (vo==null)
            throw new ServiceException(500,"记录不存在");
        if (!vo.getCode().equals(code))
            throw new ServiceException(500,"兑换码错误");

        vo.setStatus(2);
        lotteryInfoMapper.updateById(vo);
        return CommonResult.success("");
    }

    @GetMapping("/getLotteryInfo")
    @Operation(summary = "获得抽奖信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('qd:lottery:query')")
    public CommonResult getLotteryInfo(@RequestParam("id") Integer id) {
        return success(lotteryInfoMapper.selectById(id));
    }


    @PostMapping("addTestLottery")
    @Operation(summary = "添加拼团商品的记录")
    public CommonResult addTestLottery(@RequestBody AddTestLottery vo){
        GroupGoodsDO goodsDO = groupGoodsMapper.selectById(vo.getGroupGoodsId());
        if (goodsDO==null)
            throw new ServiceException(500,"查询无拼团商品");
        if (goodsDO.getStatus()!=1)
            throw new ServiceException(500,"拼团商品未上架");

        //添加拼团人数
        int adds = vo.getUsers().size();
        if (goodsDO.getBuyPerson()+adds>goodsDO.getGroupPerson()){
            int size=goodsDO.getBuyPerson()+adds-goodsDO.getGroupPerson();
            throw new ServiceException(500,"拼团人数超出"+size+"人");
        }

        //自动成团
        //活动库存减少
        goodsDO.setActNum(goodsDO.getActNum()-adds);
        int soldNum= goodsDO.getSoldNum()==null?0:goodsDO.getSoldNum();
        //已售库存增加
        goodsDO.setSoldNum(soldNum+adds);
        int buyPerson=goodsDO.getBuyPerson()==null?0:goodsDO.getBuyPerson();
        //已拼团人数
        goodsDO.setBuyPerson(buyPerson+adds);
        //活动库存请零 订单变成已结束
        if (goodsDO.getActNum()<=0){
            goodsDO.setStatus(3);
            //已支付 进行中团购订单变成普通订单
            for (GroupOrderDO groupOrderDO : groupOrderMapper.selectList(new LambdaQueryWrapper<GroupOrderDO>().eq(GroupOrderDO::getGroupGoodsId, goodsDO.getId()).eq(GroupOrderDO::getPayStatus,1).eq(GroupOrderDO::getOrderStatus,1))) {
                groupOrderDO.setOrderStatus(2);
                //团购订单状态变成已完成
                groupOrderMapper.updateById(groupOrderDO);
                //所有的团购订单转订单
                orderMapper.insert(new OrderDO(groupOrderDO));
            }
            //未支付 待付款团购订单变成失效订单
            for (GroupOrderDO groupOrderDO : groupOrderMapper.selectList(new LambdaQueryWrapper<GroupOrderDO>().eq(GroupOrderDO::getGroupGoodsId, goodsDO.getId()).eq(GroupOrderDO::getPayStatus,2).eq(GroupOrderDO::getOrderStatus,0))) {
                groupOrderDO.setOrderStatus(2);
                //团购订单状态变成已完成
                groupOrderMapper.updateById(groupOrderDO);
                //所有的团购订单转订单
                orderMapper.insert(new OrderDO(groupOrderDO));
            }

            //将该活动变成已完成
            goodsDO.setStatus(3);
        }
        groupGoodsMapper.updateById(goodsDO);

        List<LotteryInfoDO> list=new ArrayList<>();
        for (LotteryUser user : vo.getUsers()) {
            list.add(new LotteryInfoDO(user,goodsDO));
        }

        //添加记录
        lotteryInfoMapper.insertBatch(list);

        return success("");
    }


    @GetMapping("getLotteryUser")
    @Operation(summary = "获取抽奖测试用户列表")
    public CommonResult getLotteryUser(){
        List<LotteryUser> list = lotteryUserMapper.selectList(new LambdaQueryWrapper<LotteryUser>().orderByDesc(BaseDO::getCreateTime));
        Map<String,Object> map=new HashMap<>();
        map.put("list",list);
        map.put("total",list.size());
        return success(map);
    }

    @GetMapping("addLotteryUser")
    @Operation(summary = "添加测试用户")
    public CommonResult addLotteryUser(String name,String url){
        lotteryUserMapper.insert(new LotteryUser(name,url));
        return success("");
    }


    @PostMapping("/create")
    @Operation(summary = "创建抽奖")
    @PreAuthorize("@ss.hasPermission('qd:lottery:create')")
    public CommonResult<Integer> createLottery(@Valid @RequestBody LotteryDO createReqVO) {
        return success(lotteryService.createLottery(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新抽奖")
    @PreAuthorize("@ss.hasPermission('qd:lottery:update')")
    public CommonResult<Boolean> updateLottery(@Valid @RequestBody LotteryDO updateReqVO) {
        lotteryService.updateLottery(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除抽奖")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('qd:lottery:delete')")
    public CommonResult<Boolean> deleteLottery(@RequestParam("id") Integer id) {
        lotteryService.deleteLottery(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得抽奖")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('qd:lottery:query')")
    public CommonResult<LotteryDO> getLottery(@RequestParam("id") Integer id) {
        return success(lotteryService.getLottery(id));
    }

    @GetMapping("/list")
    @Operation(summary = "获得抽奖列表")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    @PreAuthorize("@ss.hasPermission('qd:lottery:query')")
    public CommonResult getLotteryList() {
        return success(lotteryMapper.selectList());
    }

    @GetMapping("/page")
    @Operation(summary = "获得抽奖分页")
    @PreAuthorize("@ss.hasPermission('qd:lottery:query')")
    public CommonResult<PageResult<LotteryDO>> getLotteryPage(@Valid LotteryPageReqVO pageVO) {
        PageResult<LotteryDO> pageResult = lotteryService.getLotteryPage(pageVO);
        return success(pageResult);
    }



    @GetMapping("/infoPage")
    @Operation(summary = "获得抽奖信息分页")
    @PreAuthorize("@ss.hasPermission('qd:lottery:query')")
    public CommonResult infoPage(@Valid LotteryPageReqVO pageVO) {
        Page<LotteryInfoDO> page = lotteryInfoMapper.selectPage(new Page<>(pageVO.getPageNo(), pageVO.getPageSize()),
                new LambdaQueryWrapper<LotteryInfoDO>()
                        .like(pageVO.getCode()!=null,LotteryInfoDO::getCode,pageVO.getCode())
                        .eq(pageVO.getId()!=null,LotteryInfoDO::getId,pageVO.getId())
                        .orderByDesc(BaseDO::getCreateTime));
        List<LotteryInfoDO> records = page.getRecords();
        for (LotteryInfoDO vo : records) {
            UserDO user = userMapper.selectById(vo.getCreator());
            if (user!=null){
                vo.setMail(user.getMail());
                vo.setPhone(user.getPhone());
            }

        }
        page.setRecords(records);
        return success(page);
    }

//    @GetMapping("/export-excel")
//    @Operation(summary = "导出抽奖 Excel")
//    @PreAuthorize("@ss.hasPermission('qd:lottery:export')")
//    @OperateLog(type = EXPORT)
//    public void exportLotteryExcel(@Valid LotteryExportReqVO exportReqVO,
//              HttpServletResponse response) throws IOException {
//        List<LotteryDO> list = lotteryService.getLotteryList(exportReqVO);
//        // 导出 Excel
//        List<LotteryExcelVO> datas = LotteryConvert.INSTANCE.convertList02(list);
//        ExcelUtils.write(response, "抽奖.xls", "数据", LotteryExcelVO.class, datas);
//    }

}
@Data
class AddTestLottery{
    //测试用户
    List<LotteryUser> users;
    //拼团活动id
    Integer groupGoodsId;
}